<template>
  <textarea :id="tinymceId" style="visibility: hidden" :disabled="isDisabled" />
</template>

<script>
import emitter from "element-ui/lib/mixins/emitter";
import loadTinymce from "@/utils/loadTinymce";
import { plugins, toolbar } from "./config";
import { debounce } from "throttle-debounce";

let num = 1;

export default {
  mixins: [emitter],
  props: {
    id: {
      type: String,
      default: () => {
        num === 10000 && (num = 1);
        return `tinymce${+new Date()}${num++}`;
      },
    },
    value: {
      default: "",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      tinymceId: this.id,
    };
  },
  inject: {
    elForm: {
      default: "",
    },
    elFormItem: {
      default: "",
    },
  },
  computed: {
    isDisabled() {
      return this.disabled || !!(this.elForm || {}).disabled;
    },
  },
  mounted() {
    loadTinymce((tinymce) => {
      // eslint-disable-next-line global-require
      require("./zh_CN");
      let conf = {};
      if (!this.isDisabled) {
        conf = {
          selector: `#${this.tinymceId}`,
          language: "zh_CN",
          menubar: "file edit insert view format table",
          plugins,
          toolbar,
          height: 300,
          branding: false,
          object_resizing: false,
          end_container_on_empty_block: true,
          powerpaste_word_import: "clean",
          code_dialog_height: 450,
          code_dialog_width: 1000,
          advlist_bullet_styles: "square",
          advlist_number_styles: "default",
          default_link_target: "_blank",
          link_title: false,
          nonbreaking_force_tab: true,
        };
      } else {
        conf = {
          selector: `#${this.tinymceId}`,
          language: "zh_CN",
          // menubar: false,
          toolbar: false,
        };
      }
      conf = Object.assign(conf, this.$attrs);
      conf.init_instance_callback = (editor) => {
        if (this.value) editor.setContent(this.value);
        if (this.isDisabled) {
          editor.setMode("readonly");
        } else {
          editor.setMode("design");
        }
        this.vModel(editor);
      };
      tinymce.init(conf);
    });
  },
  destroyed() {
    this.destroyTinymce();
  },
  methods: {
    vModel(editor) {
      // 控制连续写入时setContent的触发频率
      const debounceSetContent = debounce(250, (val) => {
        editor.setContent(val);
      });
      this.$watch("value", (val, prevVal) => {
        // if (editor && val !== prevVal && val !== editor.getContent()) {
        if (editor && val !== prevVal) {
          if (typeof val !== "string") val = val ? val.toString() : "";
          if (val !== editor.getContent()) {
            debounceSetContent.call(editor, val);
          }

          // 通知表单值变更了
          this.dispatch("ElFormItem", "el.form.change", val ? [val] : []);
        }
      });

      editor.on("change keyup undo redo", () => {
        this.$emit("input", editor.getContent());
      });
    },
    destroyTinymce() {
      if (!window.tinymce) return;
      const tinymce = window.tinymce.get(this.tinymceId);
      if (tinymce) {
        tinymce.destroy();
      }
    },
  },
};
</script>

<style lang="scss">
.tox.tox-tinymce--disabled {
  .tox-menubar,
  .tox-toolbar,
  .tox-edit-area__iframe,
  .tox-tbtn--disabled:hover {
    background-color: #f5f7fa;
  }
  .tox-tbtn--disabled:hover {
    background: url("data:image/svg+xml;charset=utf8,%3Csvg height='39px' viewBox='0 0 40 39px' width='40' xmlns='http://www.w3.org/2000/svg'%3E%3Crect x='0' y='38px' width='100' height='1' fill='%23cccccc'/%3E%3C/svg%3E")
      left 0 top 0 #f5f7fa;
  }
}
</style>
